<template>
  <div class="question-list">
    <!-- 筛选组件 -->
    <div class="question-filter">
      <el-form :inline="true"
               label-position="right"
               label-width="80px"
               :class="{'simple-filter':checkQuestionMode}"
               size="small">
        <el-row>
          <el-col :span="6">
            <el-form-item label="学科名称">
              <el-select v-model="query.subject_id"
                         placeholder="请选择学科"
                         clearable
                         @clear="get_list">
                <el-option v-for="item in treeList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="目录名称">
              <el-select v-model="query.directory_id"
                         placeholder="请选择目录"
                         clearable>
                <el-option v-for="item in directoryList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标签名称">
              <el-select v-model="query.tag_id"
                         placeholder="请选择标签"
                         clearable>
                <el-option v-for="item in tagList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="试题类型">
              <el-select v-model="query.quest_type"
                         placeholder="选择题型"
                         :disabled="qaType ? true:false"
                         clearable>
                <el-option label="单选题"
                           :value="1"></el-option>
                <el-option label="多选题"
                           :value="2"></el-option>
                <el-option label="判断题"
                           :value="3"></el-option>
                <el-option label="简答题"
                           :value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核状态">
              <el-select v-model="query.check_state"
                         :disabled="checkQuestionMode"
                         placeholder="请选择审核状态"
                         clearable>
                <el-option label="待审核"
                           :value="1"></el-option>
                <el-option label="审核通过"
                           :value="2"></el-option>
                <el-option label="不通过"
                           :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发布状态">
              <el-select v-model="query.show_state"
                         :disabled="checkQuestionMode"
                         placeholder="请选择发布状态"
                         clearable>
                <el-option label="上架"
                           :value="1"></el-option>
                <el-option label="下架"
                           :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建者">
              <el-input v-model="query.create_name"
                        placeholder="请输入创建者"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="试题难度">
              <el-select v-model="query.difficulty"
                         placeholder="请选择难度"
                         clearable>
                <el-option label="简单"
                           :value="1"></el-option>
                <el-option label="中等"
                           :value="2"></el-option>
                <el-option label="较难"
                           :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否真题">
              <el-select v-model="query.is_true_question"
                         placeholder="请选择是否真题"
                         clearable>
                <el-option label="是"
                           :value="1"></el-option>
                <el-option label="否"
                           :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="创建时间">
              <el-date-picker v-model="time"
                              type="daterange"
                              range-separator="至"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期"
                              align="right">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <!-- 简洁模式 -->
          <el-col v-if="checkQuestionMode"
                  :span="5"
                  :offset="3">
            <el-form-item>
              <el-button type="primary"
                         size="small"
                         @click="searchsubmit">查询</el-button>
              <el-button @click="searchcancel">重置</el-button>
              <el-button @click="simpleModel=!simpleModel"
                         plain
                         :icon="simpleModel ? 'el-icon-folder-remove':'el-icon-folder-add'"
                         type="warning"></el-button>

            </el-form-item>
          </el-col>
          <!-- 非简洁模式 -->
          <el-col :span="4"
                  v-else
                  :offset="4">
            <el-form-item>
              <el-button type="primary"
                         size="small"
                         @click="searchsubmit">查询</el-button>
              <el-button @click="searchcancel"
                         size="small">重置</el-button>
              <el-button @click="simpleModel=!simpleModel"
                         plain
                         size="small"
                         :icon="simpleModel ? 'el-icon-folder-remove':'el-icon-folder-add'"
                         type="warning"></el-button>

            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 列表组件 -->
    <div class="table-bg">
      <div v-if="multipleSelection.length && !checkQuestionMode">
        <el-button size="small"
                   type="success"
                   @click="changeAllShow(1)">批量上架</el-button>
        <el-button size="small"
                   type="warning"
                   @click="changeAllShow(2)">批量下架</el-button>
        <el-button size="small"
                   type="primary"
                   @click="changeAllCheck">批量通过</el-button>
        <br><br>
      </div>
      <!--   列表信息  -->
      <el-table :data="list"
                v-loading="loading"
                border
                row-key="id"
                ref="tableList"
                @selection-change="multipleSelection = $event">
        <el-table-column label="#"
                         width="60"
                         align="center"
                         type="selection"></el-table-column>
        <el-table-column label="试题信息">
          <template slot-scope="scope">
            <!-- 试题项目 -->
            <question-item :simple-model="simpleModel"
                           :question="scope.row"></question-item>
          </template>
        </el-table-column>
        <el-table-column v-if="!checkQuestionMode"
                         label="操作"
                         width="160"
                         align="center">
          <template slot-scope="scope">
            <!-- 上架：审核通过且没上架才显示 -->
            <el-button icon="el-icon-edit"
                       type="text"
                       circle
                       v-permission="'subject:directory:update'"
                       size="small"
                       v-if="scope.row.check_state==2 && scope.row.show_state==2"
                       @click="showHandler({...scope.row},1)">上架</el-button>
            <!-- 下架：上架才下架 -->
            <el-button icon="el-icon-edit"
                       type="text"
                       circle
                       v-permission="'subject:directory:update'"
                       size="small"
                       v-if="scope.row.show_state==1"
                       @click="showHandler({...scope.row},2)">下架</el-button>
            <!-- 审核：待审核状态才可显示 -->
            <el-button icon="el-icon-edit"
                       type="text"
                       circle
                       v-permission="'subject:directory:update'"
                       size="small"
                       v-if="scope.row.check_state==1"
                       @click="checkHandler({...scope.row})">审核</el-button>
            <!-- 修改：下架就可以显示 -->
            <el-button @click="editHandler({...scope.row})"
                       icon="el-icon-edit"
                       type="text"
                       circle
                       v-if="scope.row.show_state==2"
                       v-permission="'subject:directory:update'"
                       size="small">修改</el-button>
            <!-- 删除：下架就可删除 -->
            <el-button @click="delHandler({...scope.row})"
                       type="text"
                       icon="el-icon-delete"
                       size="small"
                       v-if="scope.row.show_state==2"
                       v-permission="'subject:directory:delete'"
                       circle>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页组件 -->
    <Pagination :total="total"
                :page.sync="page"
                :limit.sync="limit"
                @pagination="pagination_change" />

    <!-- 审核弹框 -->
    <el-dialog title="试题审核"
               :visible.sync="checkShow"
               width="30%"
               @close="checkCancel">
      <el-form :model="checkFormData"
               ref="checkFormData"
               label-width="80px"
               :inline="false"
               size="normal">
        <el-form-item label="审核结果">
          <el-radio-group v-model="checkFormData.check_state">
            <el-radio :label="2">通过</el-radio>
            <el-radio :label="3">不通过</el-radio>
          </el-radio-group>

        </el-form-item>
        <el-form-item label="审核意见">
          <el-input rows="3"
                    type="textarea"
                    v-model="checkFormData.check_remarks"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     @click="checkSubmit">确定</el-button>
          <el-button @click="checkCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import list from '@/mixins/list'
import { mapGetters, mapActions } from 'vuex'
import { getQuestionList, editQuestionShow, editQuestionCheck, deleteQuestion } from '@/api/exam/question'
import QuestionItem from '@/components/QuestionItem'
const defaultItem = {
  subject_id: '',
  directory_id: '',
  tag_id: '',
  difficulty: '',
  quest_type: '',
  is_true_question: '',
  show_state: '',
  check_state: '',
  create_name: ''
}
export default {
  name: 'QuestionList',
  components: {
    QuestionItem
  },
  props: {
    // 选题模式、选题模式下那么 没有一些按钮和有些选项固定死
    checkQuestionMode: {
      type: Boolean,
      default: false
    },
    // 试题类型，用于选项时候勾选
    qaType: Number
  },
  data () {
    return {
      multipleSelection: [], // 选中项
      query: { // 查询信息
        ...defaultItem,
        show_state: this.checkQuestionMode ? 1 : '',
        check_state: this.checkQuestionMode ? 2 : '',
        quest_type: this.qaType || ''
      },
      checkShow: false, // 审核表单弹框
      checkFormData: { // 审核表单
        id: '',
        check_state: 2,
        check_remarks: ''
      },
      time: [],
      simpleModel: this.checkQuestionMode // 新题模式是否简洁模式
    }
  },
  mixins: [list],
  computed: {
    ...mapGetters({
      treeList: 'subject/treeList'
    }),
    directoryList () { // 目录信息
      if (!this.query.subject_id) {
        return []
      } else {
        // eslint-disable-next-line vue/no-side-effects-in-computed-properties
        this.query.directory_id = ''
        const result = this.treeList.find(val => val.id == this.query.subject_id)
        return result.children
      }
    },
    tagList () { // 标签信息
      if (this.query.subject_id && this.query.directory_id) {
        // 取出一级
        const top = this.treeList.find(val => val.id == this.query.subject_id)
        // 取出二级
        const child = top.children.find(val => val.id == this.query.directory_id)
        return child.children
      } else {
        return []
      }
    },
    createTime () {
      if (this.time.length) {
        console.log(this.time)
        return this.time.map(val => val.getTime()).join(',')
      } else {
        return ''
      }
    }
  },
  created () {
    !this.treeList.length && this.loadTreeList()
    this.ceshi()
  },
  watch: {
    'query.subject_id': {
      deep: true,
      immediate: true,
      handler (newval, oldval) {
        if (!newval) return false
        this.loadClassList()
      }
    }
  },
  methods: {
    ceshi() {
      console.log(this.query.subject_id)
    },
    ...mapActions({
      loadTreeList: 'subject/loadTreeList'
    }),
    async get_list () {
      try {
        const { query, page, limit } = this
        query.create_time = this.createTime
        const res = await getQuestionList({ page, limit, ...query })
        this.list = res.list
        this.total = res.total
        this.loading = false
        // 设置选中行
        this.$nextTick(_ => {
          this.checkRow()
        })
      } catch (error) {
        this.loading = false
        console.log(error)
      }
    },
    // 设置表格选中行
    checkRow () {
      // 找到列表中需要选中行的信息
      if (this.multipleSelection.length) {
        // 注意 nextTick 问题
        // 留此作为纪念： 不是从选中里面去列表筛选数据，找了1天了。。。。
        // const checkRow = this.multipleSelection.filter(item => {
        //   return this.list.some(val => val.id === item.id)
        // })
        // 正确写法： 需要从列表中读取出要选中行，因为会去修改这些行的数据。所以上面思路错误了
        const checkRow = this.list.filter(item => {
          return this.multipleSelection.some(val => val.id === item.id)
        })
        checkRow.forEach(val => {
          console.log(val)
          this.$refs.tableList.toggleRowSelection(val, true)
        })
      }
    },
    searchsubmit () {
      this.page = 1
      this.get_list()
    },
    searchcancel () {
      this.page = 1
      this.query = {
        ...defaultItem,
        show_state: this.checkQuestionMode ? 1 : '',
        check_state: this.checkQuestionMode ? 2 : '',
        quest_type: this.qaType || ''
      }
      this.time = []
      this.get_list()
    },
    // 修改按钮
    editHandler (val) {
      if (val.show_state != 2) return this.$message('下架才可以修改')
      // 子父通信,传递修改id出去
      this.$emit('edit', val.id)
    },
    // 审核按钮
    checkHandler (val) {
      this.checkShow = true
      this.checkFormData.id = val.id
    },
    // 删除按钮事件
    async delHandler (val) {
      // 下架 即可删除
      if (val.show_state == 2) {
        // 删除操作
        try {
          await this.$confirm('确定删除吗,是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
        } catch (e) {
          return this.$message.info('已取消')
        }
        await deleteQuestion([val.id])
        this.$message.success('删除成功')
        // 页码退1
        if (this.page * 1 !== 1 && this.list.length === 1) {
          this.page--
        }
        this.get_list()
      } else {
        // 提示
        this.$message.warning('下架情况下才可以删除')
      }
    },
    // 审核提交
    async checkSubmit () {
      await editQuestionCheck({ checklist: [this.checkFormData] })
      this.$message.success('提交成功')
      this.get_list()
      this.checkShow = false
    },
    // 审核取消
    checkCancel () {
      this.checkFormData = {
        id: '',
        check_state: 2,
        check_remarks: ''
      }
      this.checkShow = false
    },
    // 单个上下架
    async showHandler (val, show_state) {
      await editQuestionShow({ id: [val.id], show_state })
      this.$message.success(`${show_state == 1 ? '上架' : '下架'}成功`)
      this.get_list()
    },
    // 批量上下架
    async changeAllShow (type) {
      try {
        await this.$confirm(`确定批量${type == 1 ? '上架' : '下架'}这${this.multipleSelection.length}条数据吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return this.$message.info('已取消')
      }
      if (type == 1) { // 上架,必须要审核通过的才可以
        const id = this.multipleSelection.filter(val => val.check_state === 2).map(val => val.id)
        if (id.length === 0) return this.$message.warning('所选试题都未审核通过')
        await editQuestionShow({ id, show_state: type })
        const nocheck = this.multipleSelection.length - id.length
        this.$message.success(`上架成功${id.length}条数据`)
        nocheck && this.$notify({
          title: '提示',
          message: `${nocheck}条数据还未审核通过，不能上架`,
          type: 'warning'
        })
      } else if (type == 2) { // 下架，必须处于上架状态的才可下架
        const id = this.multipleSelection.filter(val => val.show_state === 1).map(val => val.id)
        if (id.length === 0) return this.$message.warning('所选试题都已下架，无需操作')
        await editQuestionShow({ id, show_state: type })
        const nocheck = this.multipleSelection.length - id.length
        this.$message.success(`下架成功${id.length}条数据`)
        nocheck && this.$notify({
          title: '提示',
          message: `${nocheck}条数据已下架，无需操作`,
          type: 'warning'
        })
      }
      this.multipleSelection = []
      this.get_list()
    },
    // 批量审核通过
    async changeAllCheck () {
      // 只有待审核的才可以提交
      const checklist = this.multipleSelection.filter(val => val.check_state == 1).map(val => {
        return {
          id: val.id,
          check_remarks: '通过，暂无问题',
          check_state: 2
        }
      })
      if (!checklist.length) return this.$message.warning('所选数据都已审核通过')
      try {
        await this.$confirm(`确定批量审核通过这${checklist.length}条数据吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return this.$message.info('已取消')
      }

      await editQuestionCheck({ checklist })
      this.$message.success('批量审核通过成功')
      this.multipleSelection = []
      this.get_list()
    }
  }
}

</script>
<style scoped>
.question-filter {
  background-color: #fff;
  padding: 0 16px;
}
.el-date-editor.el-input__inner {
  width: 260px;
}
.question-list .el-form-item {
  margin-bottom: 10px;
}
</style>
